package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.StrategyTheme;
import cn.wolfcode.wolf2w.query.StrategyThemeQuery;
import cn.wolfcode.wolf2w.repository.StrategyThemeRepository;
import cn.wolfcode.wolf2w.service.IStrategyThemeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * Created by 甘静斌 on 2020-08-07 13:41
 */
@Service
//@Transactional
public class StrategyThemeServiceImpl implements IStrategyThemeService {

    @Autowired
    private StrategyThemeRepository repository;

    @Autowired
    private MongoTemplate template;


    @Override
    public void save(StrategyTheme strategyTheme) {
        strategyTheme.setId(null);
        repository.save(strategyTheme);
    }

    @Override
    public void update(StrategyTheme strategyTheme) {

        repository.save(strategyTheme);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public StrategyTheme get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<StrategyTheme> list() {


        return repository.findAll();
    }

    @Override
    public Page<StrategyTheme> query(StrategyThemeQuery qo) {

        //查询封装类
        Query query = new Query();

        //分页需要的数据: total -- 所有数据
        long total = template.count(query, StrategyTheme.class);
        if (total == 0){
            return Page.empty();
        }
        //分页数据 , currentPage , pageSite
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize() ,Sort.Direction.ASC,"_id");
        query.with(pageable);
        //当前页显示的数据
        List<StrategyTheme> list = template.find(query, StrategyTheme.class);

        //list Pageable total 封装三个数据,返回给页面
        return new PageImpl(list,pageable,total);
    }

    @Override
    public void saveOrUpdate(StrategyTheme strategyTheme) {

        //判断是否有id,有则修改,无则添加
        if (StringUtils.hasLength(strategyTheme.getId())){

            this.update(strategyTheme);
        }else {
            this.save(strategyTheme);
        }
    }




}
